package com.train.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.train.webadmin.app.service.*;
import com.train.webadmin.app.dao.*;
import com.train.webadmin.app.model.*;
import com.train.common.core.base.dao.BaseDaoMapper;
import com.train.common.core.constant.GlobalDeletedFlag;
import com.train.common.core.object.Tuple2;
import com.train.common.core.object.TokenData;
import com.train.common.core.object.MyRelationParam;
import com.train.common.core.object.CallResult;
import com.train.common.core.base.service.BaseService;
import com.train.common.core.util.MyModelUtil;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 学生列表数据操作服务类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Slf4j
@Service("studentInfoService")
public class StudentInfoServiceImpl extends BaseService<StudentInfo, Long> implements StudentInfoService {

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<StudentInfo> mapper() {
        return studentInfoMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public StudentInfo saveNew(StudentInfo studentInfo) {
        studentInfoMapper.insert(this.buildDefaultValue(studentInfo));
        return studentInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<StudentInfo> studentInfoList) {
        if (CollUtil.isNotEmpty(studentInfoList)) {
            studentInfoList.forEach(this::buildDefaultValue);
            studentInfoMapper.insertList(studentInfoList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<StudentInfo> studentInfoList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(studentInfoList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(studentInfoList.size(), start + batchSize);
            List<StudentInfo> subList = studentInfoList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<StudentInfo>, List<StudentInfo>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    studentInfoMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> studentInfoMapper.updateById(data));
            } else {
                studentInfoList.forEach(this::buildDefaultValue);
                studentInfoMapper.insertList(subList);
            }
            if (end == studentInfoList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(StudentInfo studentInfo, StudentInfo originalStudentInfo) {
        studentInfo.setUpdateUserId(originalStudentInfo.getUpdateUserId());
        studentInfo.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        studentInfo.setCreateTime(originalStudentInfo.getCreateTime());
        studentInfo.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<StudentInfo> uw = this.createUpdateQueryForNullValue(studentInfo, studentInfo.getId());
        return studentInfoMapper.update(studentInfo, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return studentInfoMapper.deleteById(id) == 1;
    }

    @Override
    public List<StudentInfo> getStudentInfoList(StudentInfo filter, String orderBy) {
        return studentInfoMapper.getStudentInfoList(filter, orderBy);
    }

    @Override
    public List<StudentInfo> getStudentInfoListWithRelation(StudentInfo filter, ClassInfo classInfoFilter, String orderBy) {
        List<StudentInfo> resultList =
                studentInfoMapper.getStudentInfoListEx(filter, classInfoFilter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public CallResult verifyImportList(List<StudentInfo> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "sex")) {
            callResult = verifyImportForConstDict(dataList, "sexDictMap", StudentInfo::getSex);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "nation")) {
            callResult = verifyImportForConstDict(dataList, "nationDictMap", StudentInfo::getNation);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "education")) {
            callResult = verifyImportForConstDict(dataList, "educationDictMap", StudentInfo::getEducation);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "status")) {
            callResult = verifyImportForConstDict(dataList, "statusDictMap", StudentInfo::getStatus);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "userId")) {
            callResult = verifyImportForOneToOneRelation(dataList, "SysUser", StudentInfo::getUserId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "classId")) {
            callResult = verifyImportForOneToOneRelation(dataList, "ClassInfo", StudentInfo::getClassId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "schoolId")) {
            callResult = verifyImportForOneToOneRelation(dataList, "SchoolInfo", StudentInfo::getSchoolId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    private StudentInfo buildDefaultValue(StudentInfo studentInfo) {
        TokenData tokenData = TokenData.takeFromRequest();
        studentInfo.setCreateUserId(tokenData.getUserId());
        studentInfo.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        studentInfo.setCreateTime(now);
        studentInfo.setUpdateTime(now);
        studentInfo.setDeletedFlag(GlobalDeletedFlag.NORMAL);
        return studentInfo;
    }

    @Override
    public StudentInfo getStudentInfoByUserId(Long id){
        return studentInfoMapper.getStudentInfoByUserId(id);
    }

    @Override
    public List<StudentInfo> getStudentInfoByClassId(Long classId){
        return studentInfoMapper.getStudentInfoByClassId(classId);
    }

    @Override
    public List<StudentInfo> getStudentInfoListByCreateUserId(Long createUserId) {
        return studentInfoMapper.getStudentInfoListByCreateUserId(createUserId);
    }

    @Override
    public List<StudentInfo> getStudentInfoByOfficerId(Long officerId){
        return studentInfoMapper.getStudentInfoByOfficerId(officerId);
    }

    @Override
    public List<StudentInfo> getStudentScore(StudentInfo filter, String orderBy) {
        List<StudentInfo> resultList =
                studentInfoMapper.getStudentScore(filter, orderBy);
        for (StudentInfo studentInfo : resultList) {
            studentInfo.setClassId(filter.getClassId());
        }
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }
}
